package com.gw.smscheck.controller.business.positionInfo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.gw.smscheck.entity.business.positionInfo.PositionArea;
import com.gw.smscheck.service.business.positionInfo.PositionAreaService;
import com.gw.smscheck.util.MapUtil;
import com.gw.smscheck.util.ResultConversion;
import com.gw.smscheck.util.ResultObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * PositionArea管理
 * 
 * @author wjy
 * @date 2018年11月02日
 */
@Api(description="【辖区管理】")
@Controller
@RequestMapping("/positionAreaController")
public class PositionAreaController {
	@Autowired
	private PositionAreaService positionAreaService;
	/**
	 * 跳转到编辑页面
	 * 
	 * @return
	 */
	@RequestMapping("/goEdit")
	@ApiIgnore
	public ModelAndView goEdit( PositionArea positionArea,@RequestParam("handleType") String handleType) {
		if (positionArea.getId() != null){
            positionArea = positionAreaService.findById(positionArea.getId());
		}
		ModelAndView modelAndView = new ModelAndView("views/business/position/positionAreaAdd");
        modelAndView.addObject("obj",positionArea);
        modelAndView.addObject("handleType",handleType);
		return modelAndView;
	}

	@RequestMapping(value = "/loadFile", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="读取文件插入数据", notes="读取文件插入数据")
	public String loadFile(@RequestParam("filePath") String filePath){
		try {
			File file = ResourceUtils.getFile("classpath:file/"+filePath);
			String content = readToString(file);
			JSONObject sourceObj = JSONObject.parseObject(content);
			System.out.println(sourceObj.getString("type"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return "success";
	}

	private String readToString(File file) {
		String encoding = "UTF-8";
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 添加
	 * @param response
	 * @param positionArea
	 * @return
	 */
	@RequestMapping(value = "/add", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="添加", notes="添加")
	public String add(HttpServletRequest request,HttpServletResponse response, PositionArea positionArea) {
		//User user = (User) request.getSession().getAttribute("user");
		//positionArea.setCreateUser(String.valueOf(user.getId()));
		positionArea.setType("1");//页面添加的辖区统统都是自定义辖区，状态设置为1
		positionArea.setBoundary(MapUtil.getPathString(positionArea.getBoundary()));
		return ResultObj.successResultObj(positionAreaService.add(positionArea));
	}
	/**
	 * 查询所有
	 * 
	 * @return
	 */
	@RequestMapping(value = "/findAll", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="查询所有", notes="查询所有")
	public String findAll() {
		List<PositionArea> list = positionAreaService.findAll();
		return JSON.toJSONString(list);
	}
	/**
	 * 分页查询
	 * @param positionArea
	 * @return
	 */
	@RequestMapping(value = "/pageSelect", method = { RequestMethod.POST })
	@ResponseBody
	@ApiOperation(value="分页查询", notes="分页查询")
	public String pageSelect(PositionArea positionArea) {
		PageInfo<PositionArea> pageInfo = positionAreaService.pageSelect(positionArea);
		return ResultConversion.ToEasyUIDataGrid(pageInfo).toJSONString();
	}
	/**
	 * 通过id获取
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "/findById", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="通过id获取", notes="通过id获取")
	public String findById(PositionArea dto){
		return ResultObj.successResultObj(positionAreaService.findById(dto.getId()));
	}
	/**
	 * 通过name获取
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "/findByName", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="通过名称获取", notes="通过名称获取")
	public String findByName(PositionArea dto){
		return ResultObj.successResultObj(positionAreaService.findByName(dto.getName()));
	}
	/**
	 * 修改
	 * @param positionArea
	 * @return
	 */
	@RequestMapping(value = "/update", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="修改", notes="修改")
	public String update(PositionArea positionArea) {
		return ResultObj.successResultObj(positionAreaService.update(positionArea));
	}
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delByIds", method = { RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value="批量删除", notes="批量删除")
	public String delByIds(String[] ids){
		System.out.println(ids.toString());
		return ResultObj.successResultObj(positionAreaService.delByIds(ids));
	}

    /**
     * 获取所有辖区数据（树形）
     * @return
     */
    @RequestMapping(value = "/getAreaTree", method = { RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value="获取基础辖区数据", notes="获取基础辖区数据")
	public String getAreaTree(){
	    //获取所有(根据type=2，基础辖区)
        PositionArea parm = new PositionArea();
        parm.setType("2");
        List<PositionArea> sourceList = positionAreaService.findAllByParm(parm);
        //根据city分组
        //为每一组设置子节点
        Map<String,List<String>> resultMap = new TreeMap<>();
        for(PositionArea temp : sourceList){
            if(resultMap.get(temp.getCity()) == null){
                List<String> areaList = new ArrayList<>();
                areaList.add(temp.getName());
                resultMap.put(temp.getCity(),areaList);
            }else{
                resultMap.get(temp.getCity()).add(temp.getName());
            }
        }
        //组装成父子结构
        JSONObject obj = new JSONObject();
        List<JSONObject> resultList = new ArrayList<>();
        for(Map.Entry entry : resultMap.entrySet()){
            obj.put("name",entry.getKey());
            obj.put("children",entry.getValue());
            resultList.add(obj);
        }
        return  ResultObj.successResultObj(resultList);
    }
}

